package com.etao.restaurantapi.service.impl;

import java.math.BigDecimal;
import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.ws.rs.core.MultivaluedMap;

import java.util.List;

import org.aspectj.weaver.ast.Var;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.etao.restaurantapi.service.inter.IOrderAction;
import com.etao.restaurantcore.util.DESCrypt;
import com.etao.restaurantcore.util.JsonUtil;
import com.etao.restaurantcore.util.PropertyUtils;
import com.etao.restaurantcore.util.StatusUtil;
import com.etao.restaurantentity.common.ApiMessage;
import com.etao.restaurantentity.common.Response;
import com.etao.restaurantentity.req.SupplierDishItem;
import com.etao.restaurantentity.req.TangShiOrderReq;
import com.etao.restaurantentity.resp.MealCodeApiResponse;
import com.etao.restaurantentity.resp.OrderQueryApiResponse;
import com.etao.restaurantentity.resp.OrderQueryResult;
import com.etao.restaurantentity.resp.QrApiResponse;
import com.etao.restaurantentity.resp.SaveTangShiOrderResp;
import com.etao.restaurantentity.resp.TangShiOrderBaseModel;
import com.etao.restaurantentity.servicedomain.Dine;
import com.etao.restaurantentity.servicedomain.EtsPayment;
import com.etao.restaurantentity.servicedomain.EtsPaymentOrder;
import com.etao.restaurantservice.common.ApiService;
import com.etao.restaurantservice.service.inter.IDineService;
import net.sf.json.JsonConfig;
import net.sf.json.processors.PropertyNameProcessor;

@Service
public class OrderAction implements IOrderAction {
	private static Logger logger = LoggerFactory.getLogger(OrderAction.class);
	@Autowired
	ApiService apiService;
	
	@Autowired
	private IDineService dineService;
	
	@Override
	public Response<SaveTangShiOrderResp> SaveTangShiOrder(MultivaluedMap<String, String> params) throws ParseException, Exception
	{
		logger.info(String.format("请求URL:%s 请求方式:%s 请求参数:%s", "/Api/Orders/SaveTangShiOrder","Post|application/x-www-form-urlencoded", JsonUtil.toJson(params)));
		Date startDate=new Date();

		String etaoPaymentUrl=PropertyUtils.getProperty("etao.paycenter.url");
		String etaoKaApiUrl=PropertyUtils.getProperty("etao.kaapi.url");
		String etaoKaPaymentResultUrl=PropertyUtils.getProperty("etao.kapaymentresult.url");
		
		logger.info("开始运行时间："+startDate);
		TangShiOrderReq tangShiOrder=new TangShiOrderReq();
		/*tangShiOrder=JsonUtil.map2pojo(params, TangShiOrderReq.class);*/
		tangShiOrder.setCustomerName(params.getFirst("CustomerName"));
		tangShiOrder.setIsQr(Boolean.valueOf(params.getFirst("IsQr")));
		tangShiOrder.setSource(params.getFirst("Source"));
		tangShiOrder.setPath(params.getFirst("Path"));
		tangShiOrder.setSupplierId(Integer.parseInt(params.getFirst("SupplierId")));
		tangShiOrder.setCustomerSex(params.getFirst("CustomerSex"));
		tangShiOrder.setTableNo(params.getFirst("TableNo"));
		tangShiOrder.setRemark(params.getFirst("Remark"));
		tangShiOrder.setTempOrderNumber(params.getFirst("TempOrderNumber"));
		tangShiOrder.setPayMentMethodId(Integer.parseInt(params.getFirst("PayMentMethodId")));
		tangShiOrder.setDeviceNumber(params.getFirst("DeviceNumber"));
		tangShiOrder.setEquipmentNo(params.getFirst("EquipmentNo"));
		tangShiOrder.setIsPack(Integer.parseInt(params.getFirst("IsPack")));
		tangShiOrder.setSupplierDishList(params.getFirst("SupplierDishList"));
		
		List<SupplierDishItem> dishList=JSONArray.parseArray(tangShiOrder.getSupplierDishList(),SupplierDishItem.class);
		if(tangShiOrder==null||tangShiOrder.getSupplierDishList()==null||dishList.size()==0)
		{
			Response<SaveTangShiOrderResp> exceptionResp=new Response<SaveTangShiOrderResp>();
			ApiMessage mesg=new ApiMessage();
			mesg.setMessage("传入参数错误");
			mesg.setStatusCode(10001);
			exceptionResp.setResult(null);
			exceptionResp.setMessage(mesg);
			return exceptionResp;
		}
		//调用接口查询取餐码
		Date getMealCodeStartDate=new Date();
		MealCodeApiResponse mealCodeApiResponse=apiService.apiRequestGet(MessageFormat.format("{0}/api/Dine/GetMealSequenceNo?supplierId={1}",etaoKaApiUrl,params.getFirst("SupplierId")), MealCodeApiResponse.class);
		logger.info(String.format("获取取餐码url地址:%s,返回结果:%s",MessageFormat.format("{0}/api/Dine/GetMealSequenceNo?supplierId={1}",etaoKaApiUrl,params.getFirst("SupplierId")),JsonUtil.toJson(mealCodeApiResponse)));
		Date getMealCodeEndDate=new Date();
		long getMealCodeBetween=(getMealCodeEndDate.getTime()-getMealCodeStartDate.getTime());//除以1000是为了转换成秒
		logger.info(String.format("获取取餐码总耗时:%s毫秒",getMealCodeBetween));
		String mealCode=mealCodeApiResponse.getResult();
		Dine dine=new Dine();
		dine.setMealCode(mealCode);
		dine.setOrderType("1");
		dine.setPaymentMethodId(tangShiOrder.getPayMentMethodId());
		if(tangShiOrder.getPayMentMethodId()==10)
		{
			dine.setPaymentTypeCode("WechartScanCode");
			dine.setPartnerId("1218067401");
		}
		if(tangShiOrder.getPayMentMethodId()==12)
		{
			dine.setPaymentTypeCode("AlipayScanCode");
			dine.setPartnerId("2088701474861893");
		}
		dine.setContactName(tangShiOrder.getDeviceNumber());
		dine.setCustomerNotes(tangShiOrder.getRemark() + tangShiOrder.getTempOrderNumber());
		dine.setSupplierId(tangShiOrder.getSupplierId());
		//todo 待增加订单的价格方面的东西
		BigDecimal orderTotal =new BigDecimal("0");
		for(SupplierDishItem item :dishList)
		{
			java.text.DecimalFormat   df   =new   java.text.DecimalFormat("#.00");  
			BigDecimal dec= new BigDecimal(item.getDishCount()).multiply(new BigDecimal(df.format(item.getPrice())));  
			orderTotal=orderTotal.add(dec);
		}
		dine.setOrderTotal(orderTotal);
		dine.setCustomerTotal(orderTotal);
		dine.setPath(tangShiOrder.getPath());
		dine.setTemplateid(tangShiOrder.getSource());
		dine.setSupplierDishList(dishList);
		dine.setDeskNo(tangShiOrder.getTableNo());
		Date saveTangShiOrderStartDate=new Date();
		dineService.saveTangShiOrder(dine);
		Date saveTangShiOrderEndDate=new Date();
		long saveTangShiOrderBetween=(saveTangShiOrderEndDate.getTime()-saveTangShiOrderStartDate.getTime());//除以1000是为了转换成秒
		logger.info(String.format("插入堂食订单总耗时:%s毫秒",saveTangShiOrderBetween));
		SaveTangShiOrderResp tangshi=new SaveTangShiOrderResp();
		if(tangShiOrder.getIsQr())
		{
			EtsPayment payment=new EtsPayment();
			EtsPaymentOrder paymentOrder=new EtsPaymentOrder();
			paymentOrder.setOrderId(dine.getOrderNumber());
			paymentOrder.setBody(MessageFormat.format("订单{0}在线支付业务。", dine.getOrderNumber()));
			paymentOrder.setAmount(String.valueOf(dine.getOrderTotal()));
			paymentOrder.setClientUrl("");
			paymentOrder.setRequestUrl(etaoKaPaymentResultUrl);
			paymentOrder.setAuthCode("");
			payment.setBusinessPlatformCode("BDeliveryAndroid");
			payment.setOrder(paymentOrder);
			payment.setPartnerNo(dine.getPartnerId());
			payment.setPaymentTypeCode(dine.getPaymentTypeCode());
			
			
			JsonConfig jsonConfig = new JsonConfig();  
	        PropertyNameProcessor propertyNameProcessor = new PropertyNameProcessor() {  
	            @Override  
	            public String processPropertyName(Class target, String fieldName) { 
	                return fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);  
	            }  
	        };  
	        jsonConfig.registerJsonPropertyNameProcessor(EtsPaymentOrder.class, propertyNameProcessor);  
	          
	        String json = net.sf.json.JSONObject.fromObject(payment.getOrder(), jsonConfig).toString(); 
	        
	        String encStr=DESCrypt.toHexString(DESCrypt.encrypt(json, "etaopay1")).toUpperCase();   
			
			String qr=MessageFormat.format("{0}/Home/ChannelRequest?PartnerNo={1}&PaymentTypeCode={2}&BusinessPlatformCode={3}&SignData={4}",etaoPaymentUrl,payment.getPartnerNo(),payment.getPaymentTypeCode(),payment.getBusinessPlatformCode(),encStr);
			tangshi.setQr(qr);
			Date qrApiStartDate=new Date();
			QrApiResponse qrApiResponse=apiService.apiRequestGet(tangshi.getQr(), QrApiResponse.class);
			Date qrApiEndDate=new Date();
			long qrApiBetween=(qrApiEndDate.getTime()-qrApiStartDate.getTime());//除以1000是为了转换成秒
			logger.info(String.format("获取取餐码url地址:%s,返回结果:%s",tangshi.getQr(),JsonUtil.toJson(qrApiResponse)));
			logger.info(String.format("调用易淘食支付中心获取支付二维码总耗时:%s毫秒",qrApiBetween));
			String qrResponse=qrApiResponse.getResult();
			tangshi.setQr(qrResponse);
		}
		
		tangshi.setOrderId(dine.getOrderNumber());
		Response<SaveTangShiOrderResp> resp = new Response<SaveTangShiOrderResp>();
		resp.setResult(tangshi);
		logger.info(String.format("请求URL:%s 请求方式:%s 返回参数:%s", "/Api/Orders/SaveTangShiOrder","Post|application/x-www-form-urlencoded", JsonUtil.toJson(resp)));
		Date endDate=new Date();
		long between=(endDate.getTime()-startDate.getTime());//除以1000是为了转换成秒
		logger.info(String.format("结束运行时间:%s,总耗时:%s毫秒",endDate,between));
		return resp;
	}
	
	/*@Override
	public Response<SaveTangShiOrderResp> SaveTangShiOrder(TangShiOrderReq tangShiOrder) throws ParseException, Exception
	{
		return null;*/
		/*List<SupplierDishItem> dishList=JSONArray.parseArray(tangShiOrder.getSupplierDishList(),SupplierDishItem.class);
		if(tangShiOrder==null||tangShiOrder.getSupplierDishList()==null||dishList.size()==0)
		{
			Response<SaveTangShiOrderResp> exceptionResp=new Response<SaveTangShiOrderResp>();
			ApiMessage mesg=new ApiMessage();
			mesg.setMessage("传入参数错误");
			mesg.setStatusCode(10001);
			exceptionResp.setResult(null);
			exceptionResp.setMessage(mesg);
			return exceptionResp;
		}
		//调用接口查询取餐码
		MealCodeApiResponse mealCodeApiResponse=apiService.apiRequestGet(MessageFormat.format("http://kaapi.data.etaoshi.com/api/Dine/GetMealSequenceNo?supplierId={0}",tangShiOrder.getSupplierId()), MealCodeApiResponse.class);
		String mealCode=mealCodeApiResponse.getResult();
		Dine dine=new Dine();
		dine.setMealCode(mealCode);
		dine.setOrderType("1");
		dine.setPaymentMethodId(tangShiOrder.getPayMentMethodId());
		if(tangShiOrder.getPayMentMethodId()==10)
		{
			dine.setPaymentTypeCode("WechartScanCode");
			dine.setPartnerId("1218067401");
		}
		if(tangShiOrder.getPayMentMethodId()==12)
		{
			dine.setPaymentTypeCode("AlipayScanCode");
			dine.setPartnerId("2088701474861893");
		}
		dine.setContactName(tangShiOrder.getDeviceNumber());
		dine.setCustomerNotes(tangShiOrder.getRemark() + tangShiOrder.getTempOrderNumber());
		dine.setSupplierId(tangShiOrder.getSupplierId());
		//todo 待增加订单的价格方面的东西
		BigDecimal orderTotal =new BigDecimal("0");
		for(SupplierDishItem item :dishList)
		{
			BigDecimal dec= new BigDecimal(item.getDishCount()).multiply(item.getPrice());  
			orderTotal=orderTotal.add(dec);
		}
		dine.setOrderTotal(orderTotal);
		dine.setCustomerTotal(orderTotal);
		dine.setPath(tangShiOrder.getPath());
		dine.setTemplateid(tangShiOrder.getSource());
		dine.setSupplierDishList(dishList);
		dine.setDeskNo(tangShiOrder.getTableNo());
		dineService.saveTangShiOrder(dine);
		
		SaveTangShiOrderResp tangshi=new SaveTangShiOrderResp();
		if(tangShiOrder.getIsQr())
		{
			EtsPayment payment=new EtsPayment();
			EtsPaymentOrder paymentOrder=new EtsPaymentOrder();
			paymentOrder.setOrderId(dine.getOrderNumber());
			paymentOrder.setBody(MessageFormat.format("订单{0}在线支付业务。", dine.getOrderNumber()));
			paymentOrder.setAmount("0.01");
			paymentOrder.setClientUrl("");
			paymentOrder.setRequestUrl("http://ka.paymentresult.etaoshi.com/api/PaymentResult/PaymentDineResult");
			paymentOrder.setAuthCode("");
			payment.setBusinessPlatformCode("BDeliveryAndroid");
			payment.setOrder(paymentOrder);
			payment.setPartnerNo(dine.getPartnerId());
			payment.setPaymentTypeCode(dine.getPaymentTypeCode());
			
			
			JsonConfig jsonConfig = new JsonConfig();  
	        PropertyNameProcessor propertyNameProcessor = new PropertyNameProcessor() {  
	            @Override  
	            public String processPropertyName(Class target, String fieldName) { 
	                return fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);  
	            }  
	        };  
	        jsonConfig.registerJsonPropertyNameProcessor(EtsPaymentOrder.class, propertyNameProcessor);  
	          
	        String json = net.sf.json.JSONObject.fromObject(payment.getOrder(), jsonConfig).toString(); 
	        
	        String encStr=DESCrypt.toHexString(DESCrypt.encrypt(json, "etaopay1")).toUpperCase();   
			
			String qr=MessageFormat.format("http://wechatpaytest.etaoshi.com/Home/ChannelRequest?PartnerNo={0}&PaymentTypeCode={1}&BusinessPlatformCode={2}&SignData={3}",payment.getPartnerNo(),payment.getPaymentTypeCode(),payment.getBusinessPlatformCode(),encStr);
			tangshi.setQr(qr);
			QrApiResponse qrApiResponse=apiService.apiRequestGet(tangshi.getQr(), QrApiResponse.class);
			String qrResponse=qrApiResponse.getResult();
			tangshi.setQr(qrResponse);
		}
		
		tangshi.setOrderId(dine.getOrderNumber());
		Response<SaveTangShiOrderResp> resp = new Response<SaveTangShiOrderResp>();
		resp.setResult(tangshi);
		return resp;*/
	/*}*/
	
	/*
	 * Description：1.2 请求订单打印序号协议
	 * Author:xupeng
	 * 返回值：取餐码*/
	public Response<Integer> selectDine(String orderNumber,String deviceNumber){
		Dine model=new Dine();
		//model.setOrderNumber(String.valueOf(orderNumber));
		model.setOrderNumber(orderNumber);

		Response<Integer> resp=new Response<Integer>();
		try
		{
			String mealCode=dineService.selectOne(model).getMealCode();

			resp.setResult(Integer.parseInt(mealCode));
		}
		catch(Exception e)
		{
			resp.setResult(0);
		}
		return resp;
	}

	/*
	 * Description：1.5 主动请求查看是否支付成功
	 * Author:xupeng
	 * 返回值：取餐码*/
	public Response<TangShiOrderBaseModel> getOrderWithOtherPlatform(String id,int orderType,int orderSourceType){
		
		Response<TangShiOrderBaseModel> result=new Response<TangShiOrderBaseModel>();
		
		Dine parameter=new Dine();
		parameter.setOrderNumber(id);
		
		Dine model=dineService.selectOne(parameter);
		if(model==null||model.getDineId()<1){
			ApiMessage message=new ApiMessage();
			message.setStatusCode(20007);			
			message.setMessage(StatusUtil.GetInstance().GetMessage("20007"));
			
			result.setMessage(message);
			return result;
		}
		
		TangShiOrderBaseModel item=new TangShiOrderBaseModel();
		//item.setOrderNumber(Integer.parseInt(model.getOrderNumber()));
		item.setOrderNumber(model.getOrderNumber());
		item.setDateReserved(model.getCreatTime());
		item.setPaymentId(model.getPaymentMethodId());
		item.setTableStatus(model.getOrderStatusId());
		item.setCustomerTotal(model.getCustomerTotal());
		item.setIsConfirm(true);
		item.setIsPaId(model.getIsPaid());
		item.setDeviceNumber(model.getContactName());

		if(model.getIsPaid()){
			
			result.setResult(item);
			return result;
		}
				
		//注意：小于0.01元是不会向支付宝提交订单的
		BigDecimal bDecimal=new BigDecimal("0.01");
		if(model.getPaymentMethodId()==12 && model.getCustomerTotal().compareTo(bDecimal) < 0){
			model.setIsPaid(true);
			
			dineService.updateIsPaid(model);
			item.setIsPaId(true);

			result.setResult(item);
			return result;
		}
			
		//必须支付方式、商户号、支付方式编码不为空时，才去查询支付平台
		if(model.getPaymentMethodId()==0||model.getPartnerId()==null||model.getPartnerId().isEmpty()||model.getPaymentTypeCode()==null||model.getPaymentTypeCode().isEmpty()){
			item.setIsPaId(false);

			result.setResult(item);
			return result;
		}
		
		String cUrl=PropertyUtils.getProperty("etao.paycenter.url");
		
		//如果库内未支付则去查询第三方支付平台	
		String orderQueryUrl=MessageFormat.format("{0}/home/OrderQuery?orderNo={1}&paymentTypeCode={2}&partnerNo={3}",cUrl,model.getOrderNumber(),model.getPaymentTypeCode(),model.getPartnerId());
		OrderQueryApiResponse orderQueryApiResponse=apiService.apiRequestGet(orderQueryUrl, OrderQueryApiResponse.class);
		logger.info(String.format("获取订单支付状态url地址:%s,返回结果:%s",orderQueryUrl,JsonUtil.toJson(orderQueryApiResponse)));
		if(orderQueryApiResponse==null||orderQueryApiResponse.getResult()==null){
			item.setIsPaId(false);
		}				
		else{
			List<OrderQueryResult> orderQueryResultList=orderQueryApiResponse.getResult();
			if(orderQueryResultList!=null&orderQueryResultList.size()==1){
				item.setIsPaId(orderQueryResultList.get(0).getPaymentStatus()==5);
			}
			else{
				item.setIsPaId(false);
			}
				
		}
		result.setResult(item);
		return result;
	}
	
}